# -*- encoding: utf-8 -*-

def stdimg(instance, image):
    '''
    standarization of image fields (for being used when saving models)
      change image name to /path/to/images/<my_field>-<id>.<ext>
      resize image to specified size
    arguments:
      instance: model instance to be saved
      image: tuple containing image field name, and desired size (a tuple containing width and height)
    example:
      class MyModel(models.Model):
        my_image = models.ImageField(upload_to='path/to/images')

        def save(self):
          super(MyClass, self).save() # We force to save and create an object id to use in image name
          stdimg(self, ('my_image', (640, 480)))
          super(MyClass, self).save() # We update paths on db
    '''

    import os
    from django.conf import settings
    from PIL import Image
    src = eval('instance.%s.name' % image[0])
    old_name = os.path.join(settings.MEDIA_ROOT, src).encode('utf-8')
    if src:
        ext = os.path.splitext(src)[1].lower().replace('jpeg', 'jpg')
        filename = lambda s: instance._meta.get_field(s).get_filename('%s-%s%s' % (s, instance.id, ext))

    if image:
        img = Image.open(open(old_name, 'rb'))
        new_name = os.path.join(os.path.dirname(old_name), filename(image[0]))

        size = image[1]
        x, y = size[0], float(img.size[1]) / img.size[0] * size[0]
        pos_x, pos_y = 0, float(y - size[1]) / 2
        img = img.resize((x,y), Image.ANTIALIAS)
        img = img.crop((pos_x, pos_y, pos_x + size[0], pos_y + size[1]))
        img.save(new_name)
        setattr(instance, image[0], os.path.join(os.path.dirname(src), filename(image[0])))
        
    if os.path.exists(old_name) and src != os.path.join(os.path.dirname(src), filename(image[0])):
        os.remove(old_name)
